﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using wms.Common;
using wms.Model;

namespace wms.Pages
{
    /// <summary>
    /// GoodsList.xaml 的交互逻辑
    /// </summary>
    public partial class GoodsList : Page
    {
        private DataTable dt = null;

        public TypeModel Value { get; set; }
        private DataTable dtree;
        private TypeModel root;

        public GoodsList()
        {
            ChangeLanguage.changePage(Variable.LanguageSeesion.ToString());
            InitializeComponent();
        }

        private void loadTree(TypeModel node)
        {

            DataRow[] childrenRows = dtree.Select("pid = " + node.Id);
            foreach (DataRow row in childrenRows)
            {
                TypeModel child = new TypeModel((int)row["id"], row["name"] as string);
                child.Parent = node;
                node.Childern.Add(child);
                loadTree(child);
            }
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
           
            query("","");
            this.btnBar.ButtonDelete.IsEnabled = this.dataGrid.SelectedIndex == -1 ? false : true;

            //加载树形物品类别
            string sql = "select id,pid,name,fullname from t_type";
            dtree = DBHelper.GetDataTable(sql, new Dictionary<string, object>());
            root = new TypeModel(-1, "所有分类");
            if (dtree.Columns.Count > 0)
            {
                loadTree(root);
            }
            ObservableCollection<TypeModel> list = new ObservableCollection<TypeModel>();
            list.Add(root);

            this.treeView.ItemsSource = list;
        }

        private void btn_query_Click(object sender, RoutedEventArgs e)
        {
            this.pagination.Reset();
            query(this.txt_name.Text, this.txt_type.Text);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="name">物品名称</param>
        /// <param name="type">物品类型</param>
        private void query(string name,string type)
        {
            string sql = "select id,code,name,type,size,value,dbo.f_goods_quantity(id) as quantity,weight from t_goods where name like '%' + @name + '%' and type like '%' + @type + '%'";

            dt = DBHelper.GetDataTable(sql, new Dictionary<string, object> { { "@name", name}, { "@type",type} }, "id", this.pagination.PagePer, this.pagination.Offset);
            dataGrid.ItemsSource = dt.DefaultView;
            int count = DBHelper.GetCount(sql, new Dictionary<string, object> { { "@name", name}, { "@type",type } });
            this.pagination.Init(count);
        }

        private void btn_refresh_Click()
        {
            query("","");
        }

        private void btn_export_Click()
        {

            if (dt == null)
            {
                MessageBox.Show("没有需要导出的数据");
                return;
            }

            Dictionary<string, string> mapping = new Dictionary<string, string>();
            mapping.Add("name", "物品名称");
            mapping.Add("code", "物品编码");
            mapping.Add("quantity", "物品数量");
            mapping.Add("weight", "重量(kg)");
            mapping.Add("size", "物品尺寸");
            mapping.Add("value", "声明价值");
            mapping.Add("type", "物品类型");

            System.Windows.Forms.SaveFileDialog sd = new System.Windows.Forms.SaveFileDialog();
            sd.Filter = "Excel 2003 文档|*.xls";
            if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (File.Exists(sd.FileName))
                {
                    File.Delete(sd.FileName);
                }
                ExcelHelper.TableToExcel(dt, mapping, sd.FileName);
                if (MessageBox.Show("导出完毕，是否现在打开？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    System.Diagnostics.Process.Start(sd.FileName);
                }
            }
        }

        private void btn_import_Click()
        {
            new GoodsImport().ShowDialog();
            query(this.txt_name.Text, this.txt_type.Text);
        }

        private void btn_delete_Click()
        {
            string message = "";
            IList list = this.dataGrid.SelectedItems as System.Collections.IList;
            if (list == null || list.Count == 0)
            {
                MessageBox.Show("没有选中项");
                return;
            }

            if (MessageBox.Show("确定删除选中物品？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                foreach (var item in list)
                {
                    DataRow row = (item as DataRowView).Row;
                    DataTable dt = DBHelper.GetDataTable(string.Format("SELECT * from t_record_in_item where goods_id='{0}'", row["id"]));
                    DataTable dt1 = DBHelper.GetDataTable(string.Format("SELECT * from t_record_out_item where goods_id='{0}'", row["id"]));
                    //物品正在做入库或者出库，不能删除
                    if (dt.Rows.Count > 0 || dt1.Rows.Count > 0)
                    {
                        message += string.Format("物品名称【{0}】,正在处理中，不能删除！\r\n", row["name"]);
                    }
                    else
                    {
                        int r = DBHelper.ExcuteSQL("delete t_goods where id = @id", new SqlParameter[] { new SqlParameter("id", row["id"]) }, CommandType.Text);
                    }
                }
                query("","");
                if (message != "")
                {
                    MessageBox.Show(message);
                }
            }
        }

        private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.btnBar.ButtonDelete.IsEnabled = this.dataGrid.SelectedIndex == -1 ? false : true;
        }

        private void dataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataRowView drv = this.dataGrid.SelectedItem as DataRowView;
            if (drv != null)
            {
                GoodsInput gi = new GoodsInput(Utils.ParseToDictionary(drv.Row));
                gi.Closed += Gi_Closed;
                gi.ShowDialog();
            }
        }

        private void Gi_Closed(object sender, EventArgs e)
        {
            query(this.txt_name.Text, this.txt_type.Text);
        }

        private void btn_type_Click()
        {
            Type type = new Type();
            bool? r = type.ShowDialog();
        }

        private void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            TypeModel item = this.treeView.SelectedItem as TypeModel;
            if (item != null)
            {
                if (item.Id == -1)
                {
                    this.txt_type.Text = "";
                }
                else
                {
                    this.txt_type.Text = item.Name;
                }
                query("", this.txt_type.Text);
            }
        }

        private void btn_print_Click()
        {
            IList list = this.dataGrid.SelectedItems as IList;
            if (list == null || list.Count == 0)
            {
                MessageBox.Show("没有选中项");
                return;
            }
            DataTable dt = new DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("code");
            dt.Columns.Add("quantity");
            dt.Columns.Add("weight");
            dt.Columns.Add("type");
            dt.Columns.Add("size");
            dt.Columns.Add("value");

            foreach (var item in list)
            {
                DataRow row = (item as DataRowView).Row;
                DataRow dr = dt.NewRow();
                dr["name"] = row["name"];
                dr["code"] = row["code"];
                dr["quantity"] = row["quantity"];
                dr["weight"] = row["weight"];
                dr["type"] = row["type"];
                dr["size"] = row["size"];
                dr["value"] = row["value"];
                dt.Rows.Add(dr);

            }
            GoodsPrint gp = new GoodsPrint(dt);
            gp.ShowDialog();
        }
    }
}
